<template>
  <div>
    <div class="scene-head">图片智能在线设计 -> 选择模板</div>
    <div class="choose-option-box">
      <div class="tab-box">
        <span class="tab-title">分类：</span>
        <div class="class-box">
          <span class="class-item" :class="{'active': !class_id}" @click="chooseIt({class_id: ''},'class')">全部</span>
          <span class="class-item" v-for="item in class_list" :key="item.class_id" :class="{'active': class_id === item.class_id}" @click="chooseIt(item,'class')">{{item.name}}</span>
        </div>
      </div>

      <div class="tab-box">
        <span class="tab-title">场景：</span>
        <div class="class-box" :style="{height: showMore1?'auto':''}">
          <span class="class-item" :class="{'active': !scene_id}" @click="chooseIt({scene_id: ''},'scene')">全部</span>
          <span class="class-item" v-for="item in scene_list" :key="item.scene_id" :class="{'active': scene_id === item.scene_id}" @click="chooseIt(item,'scene')">{{item.name}}</span>
        </div>
        <span class="more-box" v-if="scene_list.length > 13"><span @click.stop="toShowMore('showMore1')" style="cursor: pointer;">{{showMore1?'收起':'更多'}}</span> <i class="iconfont" :class="[showMore1?'icon-member-top':'icon-member-bottom']"></i></span>
      </div>

      <div class="tab-box">
        <span class="tab-title">行业：</span>
        <div class="class-box" :style="{height: showMore2?'auto':''}">
          <span class="class-item" :class="{'active': !industry_id}" @click="chooseIt({industry_id: ''},'industry')">全部</span>
          <span class="class-item" v-for="item in industry_list" :key="item.industry_id" :class="{'active': industry_id === item.industry_id}" @click="chooseIt(item,'industry')">{{item.name}}</span>
        </div>
        <span class="more-box" v-if="industry_list.length > 13"><span @click.stop="toShowMore('showMore2')" style="cursor: pointer;">{{showMore2?'收起':'更多'}}</span> <i class="iconfont" :class="[showMore2?'icon-member-top':'icon-member-bottom']"></i></span>
      </div>

      <div class="set-box">
        <div class="order-choose">
          <span class="choose-item" @click="chooseIt(3,'sort')" :class="{'choose-active': sort_type == 3}">热门推荐</span>
          <span class="choose-item" @click="chooseIt(1,'sort')" :class="{'choose-active': sort_type == 1}">最多上传</span>
          <span class="choose-item" @click="chooseIt(2,'sort')" :class="{'choose-active': sort_type == 2}">最多使用</span>
        </div>

        <div class="option-filters-line"></div>

        <a-popover title="" placement="bottom" :visible="colour_show" trigger="hover" @visibleChange="handleColorHoverChange">
          <template slot="content">
            <div class="color-choose">
              <div class="color-item" @click="chooseIt({colour_id: '',colour_id_text:''},'colour')"><img class="color-img" src="../../resource/images/color.png" alt=""/></div>
              <div v-for="color in colour_list" @click="chooseIt(color,'colour')" class="color-item" :style="{backgroundColor: color.colour_number}"></div>
            </div>
          </template>
          <div class="choose-box">
            <span class="choose-title">颜色：</span>
            <div class="choose-content">
              <img class="color-img" v-if="!colour_id" src="../../resource/images/color.png" alt="">
              <div class="color-box" v-if="colour_id" :style="{backgroundColor: colour_id_text}"></div>
              <a-icon type="caret-down" />
            </div>
          </div>
        </a-popover>

        <div class="option-filters-line"></div>

        <a-popover title="" placement="bottom" :visible="style_show" trigger="hover" @visibleChange="handleHoverChange">
          <template slot="content">
            <p class="style-box">
              <span :class="{active: !style_id}" @click="chooseIt({style_id: '',name: '全部'},'style')">全部</span>
              <span :class="{active: style_id == style_item.style_id}" v-for="style_item in style_list" @click="chooseIt(style_item,'style')" :key="style_item.style_id">{{style_item.name}}</span>
            </p>
          </template>
          <div class="choose-box">
            <span class="choose-title">风格：</span>
            <div class="choose-content">
              <span style="margin-right: 3px;">{{style_id_text}}</span><a-icon type="caret-down" />
            </div>
          </div>
        </a-popover>

        <div class="option-filters-line"></div>

        <div class="choose-box">
          <span class="choose-title">价格：</span>
          <div class="order-choose">
            <span class="choose-item" @click="chooseIt(2,'price')" :class="{'active': price_type == 2}">全部</span>
            <span class="choose-item" @click="chooseIt(0,'price')" :class="{'active': price_type == 0}">免费</span>
            <span class="choose-item" @click="chooseIt(1,'price')" :class="{'active': price_type == 1}">会员免费</span>
          </div>
        </div>
      </div>
    </div>

    <div class="main" ref="main">
      <!--v-for="(list, index) in picture_list" :key="index"-->
      <ul class="picture-box" ref="pictureBox">
        <!--<li class="picture-item">-->
          <!--<div class="picture-top">-->
            <!--<img class="picture-img" src="../../resource/images/empty_img.png" alt="">-->
          <!--</div>-->
          <!--<span style="text-align: center;" class="picture-name">开启空白画布</span>-->
        <!--</li>-->
        <li class="picture-item" v-for="item in data_list.queryDesignTemplateBeanList" :key="item.designTemplateId" @click="clickDesign(item)">
          <div class="picture-top">
            <img class="picture-img" :src="item.cutDownTemplateImageUrl" alt="">
            <!--<p class="picture-type">{{item.designKindName}} {{item.width}}*{{item.height}}</p>-->
            <div class="preview" @click.stop="openOverlay($event, item)" ><i class="iconfont icon-ht_operation_perview"></i></div>
          </div>
          <span class="picture-name">{{item.width}}*{{item.height}} {{item.templateTitle}}</span>
        </li>
      </ul>
    </div>

    <div>
      <a-pagination
          style="margin-top: 15px;text-align: center"
          showQuickJumper
          :pageSize="main_page_pagination.pageSize"
          :current="main_page_pagination.current"
          :total="main_page_pagination.total"
          @change="getTemplate"/>
    </div>

    <div class="overlay" v-if="showOverlay" @click="closeOverlay">
      <div class="overlay-img-box">
        <img class="overlay-img" :style="{width: overlayImgW,height: overlayImgH}" :src="overlayImg" alt="" />
      </div>
    </div>

    <a-modal v-model="visible" :width="800" title="保存在线设计图片" on-ok="handle_confirm">
      <div>
        <span>保存到商城附件：</span>
        <a-radio-group :options="plainOptions" @change="onChange" />
        <a-button type="primary" @click="downloadOrigin">
          保存
        </a-button>
      </div>
      <p style="margin: 20px 0;">点击保存，返回选择图片即可直接使用</p>
      <div>
        <span>下载到本地：</span>
        <a-button type="primary" @click="download">
          下载
        </a-button>
      </div>

      <template slot="footer">
        <div style="text-align: center;">
          <a-button style="height: 40px;width: 100px;" @click="handle_confirm">
            取消
          </a-button>
        </div>
      </template>
    </a-modal>

  </div>
</template>

<script>
import CryptoJS from "@/core/crypto-js";
const plainOptions = ['jpg', 'png', 'gif'];
export default {
	// https://api-v2.chuangkit.com/designkind/getDesignTypeV2.do?_dataType=json
	data () {
		return {
			plainOptions,
			ext: '',
			visible: false,
      initData: {},

			showMore1: false,
			showMore2: false,
      showOverlay: false,
			overlayImg: "",
			overlayImgW: "",
			overlayImgH: "",
			style_show: false,
			colour_show: false,
			download_url: [],

			class_list: [],
			colour_list: [],
			industry_list: [],
			scene_list: [],
			style_list: [],
			data_list: [],
			picture_list: [],

			class_id: '',
			scene_id: '',
			industry_id: '',
			colour_id: '',
			colour_id_text: '',
			style_id: '',
			style_id_text: '全部',
			sort_type: 3, //排序类型 1：最新上传2：最多使用3：热门推荐
			price_type: 0, //价格类型 0：免费1：收费2：全部
			page_no: 1,
			// 主分页的页码
			main_page_pagination: {
				current: 1,
				pageSize: 20,
				total: 0
			},
		};
	},
  created() {
		this.getInit();
  },
  mounted() {
		if(this.$route.query.class_id) {
			this.class_id = Number(this.$route.query.class_id);
    }
	  if(this.$route.query.kindId) {
		  this.scene_id = Number(this.$route.query.kindId);
	  }
		this.getTemplate();
		// window.onresize = ()=>{
		// 	let picture_length = Math.floor((this.$refs.main.offsetWidth-100)/210);
		// 	this.init(picture_length);
		// }
	  // pc创可贴回调函数
	  window.chuangkitComplete = this.chuangkitComplete;
  },
  methods: {
	  handle_confirm() {
		  this.visible = false;
	  },
	  onChange(e) {
		  this.ext = e.target.value;
    },
    download() {
	  	for(let i = 0;i<this.download_url.length;i++) {
			  window.open(this.download_url[i])
      }
	    this.visible = false;
    },
	  downloadOrigin() {
	  	if(!this.ext) {
			  this.$message.error('请先选择文件后缀！');
	  		return;
      }
		  $http.post("plugin.decorate.frotend.ckt.fetch", {
			  success_url: 'https:'+ this.download_url[0],
			  ext: this.ext
      },'load').then(response=> {
			  if (response.result === 1) {
				  this.$message.success('保存成功！可在选择图片列表直接使用');
				  this.visible = false;
        } else {
				  if (response.msg) {
					  this.$message.error(response.msg);
				  }
			  }
		  })
    },
	  chuangkitComplete(res) {
		  console.log("收到创客贴回调参数:", res)
		  if (!res.cktMessage) {
			  this.$message.error('回调失败');
			  return;
		  }
		  if(!res['design-id']) {
		  	// 取消
		  	return;
      }
      this.download_url = res['source-urls'];
      this.visible = true;
    },
		clickDesign(item) {
			// const getSign = (params, key) => {
			// 	let pArr = []
			// 	for (let key in params) {
			// 		pArr.push(`${key}=${params[key]}`)
			// 	}
			// 	return CryptoJS.MD5(pArr.sort().join('&') + key).toString().toUpperCase()
			// };

			const getParams = () => {
				// const app_skey = '7B50C5B1723AC5FE51CC4E971F9017B0'; // 企业秘钥
				let defaultParams = {
          ...this.initData,
					// app_id: this.app_id, // 企业appID
					expire_time: Date.now() + 1000 * 1000, // 过期时间
					// user_flag: this.user_flag, // 用户唯一标识
					device_type: 1, // pc: 1 mobile: 2
					// kind_id: '166' // 场景ID
					template_id: item.designTemplateId, // 场景ID
					download_mime : 0,
				};
				const mParams = {
					...defaultParams,
				};
				let params = Object.assign(defaultParams, mParams);
				return {
					...params,
					// sign: getSign(params, app_skey)
				}
			};

			let params = getParams()
      this.getSign(params);
			// console.log('参数:', params);
			// const design = new CktDesign(params);
			// design.open();
    },
	  handleColorHoverChange(value) {
      this.colour_show = value;
    },
	  handleHoverChange(value) {
		  this.style_show = value;
    },
	  chooseIt(item, key) {
			switch (key) {
        case 'class':
        	this.class_id = item.class_id;
	        this.scene_id = "";
	        this.industry_id = "";
	        break;
				case 'scene':
					this.scene_id = item.scene_id;
					this.industry_id = "";
					break;
				case 'industry':
					this.industry_id = item.industry_id;
					break;
				case 'colour':
					this.colour_id = item.colour_id;
					this.colour_id_text = item.colour_number;
					this.colour_show = false;
					break;
				case 'style':
					this.style_id = item.style_id;
					this.style_id_text = item.name;
					this.style_show = false;
					break;
				case 'sort':
					this.sort_type = item;
					break;
				case 'price':
					this.price_type = item;
					break;
        default:
        	break;
      }

      this.getTemplate(1);
    },
	  toShowMore(key){
	  	this[key] = !this[key];
    },
	  openOverlay(event, item) {
	  	this.overlayImg = item.designTemplateImageUrl;
		  this.showOverlay = true;
		  if(Number(item.height.substring(0,item.height.length-2)) < 400) {
		  	this.overlayImgH = '50%'
      }
		  if(Number(item.height.substring(0,item.height.length-2)) > 1000) {
			  this.overlayImgW = '50%'
		  }
    },
	  closeOverlay(){
		  this.showOverlay = false;
		  this.overlayImgH = '';
		  this.overlayImgW = '';
    },
	  getInit() {
	    $http.post("plugin.decorate.frotend.ckt.getIni").then(response=> {
		    if (response.result === 1) {
		    	this.initData = response.data;
		    	delete this.initData.is_auth;
		    	console.log(this.initData)
		    } else {
			    if (response.msg) {
				    this.$message.error(response.msg);
			    }
		    }
	    });
    },
	  getSign(params) {
		  $http.post("plugin.decorate.frotend.ckt.getSign", {params}).then(response=> {
			  if (response.result === 1) {
				  let design_params = {
					  ...params,
					  sign: response.data.sign
				  };
				  console.log('参数:', design_params);
				  const design = new CktDesign(design_params);
				  design.open();
			  } else {
				  if (response.msg) {
					  this.$message.error(response.msg);
				  }
			  }
		  });
	  },
	  getTemplate(page_no) {
		  $http.post("plugin.decorate.frotend.ckt.getList", {
			  class_id: this.class_id,
			  scene_id: this.scene_id,
			  industry_id: this.industry_id,
			  colour_id: this.colour_id,
			  style_id: this.style_id,
			  sort_type: this.sort_type,
			  price_type: this.price_type,
			  page_no: page_no || 1
		  }, "loading").then(response => {
			  if (response.result === 1) {
				  this.class_list = response.data.class_list;
				  this.scene_list = response.data.scene_list;
				  this.industry_list = response.data.industry_list;
				  this.style_list = response.data.style_list;
				  this.colour_list = response.data.colour_list;

				  this.data_list = response.data.data_list;
				  this.main_page_pagination.current = page_no || 1;
				  this.main_page_pagination.total = this.data_list.totalCount;
				  // this.$refs.main.style.display = 'block';
				  // let picture_length = Math.floor((this.$refs.main.offsetWidth-100)/210);
				  // this.init(picture_length);
			  } else {
				  if (response.msg) {
					  this.$message.error(response.msg);
				  }
			  }

		  }).catch(err => {
			  console.log(err);
		  });
	  },

	  init(picture_length) {
		  this.picture_list = [];
		  for(let i = 0;i < picture_length;i++) {
			  this.picture_list.push([])
		  }
		  this.sort(0, this.data_list.queryDesignTemplateBeanList);
	  },
	  sort(arg, list) {
		  let that = this;
		  let index = arg || 0;
		  if (list && list.length > 0 && list.length > index) {
			  if (list[index].cutDownTemplateImageUrl) {
			  	console.log(index)
				  that.getImg(
						  list[index].cutDownTemplateImageUrl,
						  function() {
							  that.setArrays(list, index);
						  },
						  function() {
							  list[index].cutDownTemplateImageUrl = "https://www.yunzmall.com/min_img/img_404.png";
							  that.$nextTick(() => {
								  that.sort(index, list);
							  });
						  }
				  );
			  } else {
				  that.setArrays(list, index);
			  }
		  }

		  if (list.length == index) {
		  	setTimeout(()=>{
				  this.$refs.main.style.display = 'flex';
        },20);
		  }
	  },
	  setArrays(list, index) {
		  let boxIndex = 0;
		  let min = "";
		  if(this.$refs.pictureBox.length > 1) {
			  min = this.$refs.pictureBox[0].clientHeight;
			  for(let i = 0;i<this.$refs.pictureBox.length;i++) {
				  if(this.$refs.pictureBox[i].clientHeight < min){
					  min = this.$refs.pictureBox[i].clientHeight;
					  boxIndex = i;
				  }
			  }
      }

		  this.picture_list[boxIndex].push(list[index]);
		  this.$nextTick(() => {
			  this.sort(index + 1, list);
		  });
	  },
	  // 图片加载完回调
	  getImg(url, callback, callback2) {
		  let img = new Image();
		  img.src = url;
		  // console.log("完全加载完毕的事件================", img);
		  //如果图片被缓存，则直接返回缓存数据
		  if (img.complete) {
			  /* callback(img.width, img.height); */
			  callback(img.width, img.height, Number(img.height) / Number(img.width));
		  } else {
			  //完全加载完毕的事件
			  img.onload = function() {
				  /* callback(img.width, img.height); */
				  callback(img.width, img.height, Number(img.height) / Number(img.width));
			  };
			  img.onerror = function() {
				  console.log("图片链接error:: 404", img);
				  callback2();
			  };
		  }
	  },
  }
};
</script>

<style lang="less" scoped>
  .scene-head {
    padding: 20px 30px;
    border-bottom: 1px solid #ebeef5;
    font-size: 16px;
  }
  .choose-option-box {
    padding: 15px 20px;
  }
  .tab-box {
    display: flex;
    padding-bottom: 10px;
    border-bottom: 1px solid #EFEFEF;
  }
  .tab-title {
    color: #000000;
    padding: 10px;
    flex: 0 0 80px;
    font-weight: 700;
  }
  .more-box {
    padding: 10px;
    flex: 0 0 80px;
  }
  .class-box {
    display: flex;
    flex-wrap: wrap;
    height: 40px;
    overflow: hidden;
  }
  .class-item {
    padding: 5px 10px;
    cursor: pointer;
    margin: 5px 0;
  }
  .class-item:hover {
    color: #29BA9C;
  }
  .class-item.active {
    background-color: rgba(41, 186, 156, 0.20);
    color: #29BA9C;
    border-radius: 5px;
  }

  .set-box, .order-choose, .choose-box, .choose-content {
    display: flex;
    align-items: center;
  }
  .set-box {
    margin: 10px 0;
  }
  .option-filters-line {
    width: 2px;
    height: 8px;
    background: #ebeef5;
    margin: 0 24px;
  }
  .choose-active, .choose-title {
    color: #000000;
    font-weight: 700;
  }
  .choose-item {
    padding: 0 10px;
    cursor: pointer;
  }
  .choose-item.active {
    background-color: rgba(41, 186, 156, 0.20);
    color: #29BA9C;
    padding: 5px 10px;
  }
  .choose-content {
    background-color: rgba(41, 186, 156, 0.20);
    color: #29BA9C;
    padding: 5px 10px;
    font-size: 12px;
    border-radius: 5px;
    cursor: pointer;
    .color-img, .color-box {
      width: 18px;
      height: 18px;
      border-radius: 50%;
      margin-right: 3px;
    }
  }

  .color-choose {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    width: 80px;
    .color-img {
      width: 30px;
      height: 20px;
      border-radius: 3px;
      margin-top: -3px;
    }
    .color-item {
      width: 30px;
      height: 20px;
      margin: 5px;
      border-radius: 3px;
      cursor: pointer;
    }
  }

  .style-box {
    display: flex;
    flex-direction: column;
    height: 150px;
    min-width: 80px;
    overflow-y: scroll;
    text-align: center;
    span {
      cursor: pointer;
      padding: 3px 0;
    }
    span.active {
      color: #000000;
      font-weight: 700;
    }
    &::-webkit-scrollbar {display:none}
  }

  .main {
    /*display: flex;*/
  }
  .picture-box {
    /*width: 210px;*/
    /*display: inline-block;*/
    /*display: flex;*/
    /*flex-direction: column;*/
    /*column-count: 6;*/
    column-width: 210px;
    /*column-gap: 10px;*/
    /*display: flex;*/
    /*flex-wrap: wrap;*/
    margin: 10px 20px 20px 10px;
  }
  .picture-item {
    /* 防止多列布局，分页媒体和多区域上下文中的意外中断 */
    break-inside: avoid;
    list-style: none;
    display: flex;
    flex-direction: column;
    width: 200px;
    padding: 10px 0 10px 0;
    .picture-top {
      cursor: pointer;
      position: relative;
      transition: transform 0.5s ease;
      .picture-type {
        position: absolute;
        background-color: #ffffff;
        color: #000000;
        font-weight: 600;
        bottom: -35px;
        width: 100%;
      }
      .preview {
        background-color: #ffffff;
        padding: 0px 5px;
        border-radius: 3px;
        position: absolute;
        top: 15px;
        left: 10px;
        display: none;
      }
      &:hover{
        border-radius: 5px;
        box-shadow: 3px 3px 12px #c7c7c7;
        transform: scale(1.05);
        .picture-type, .preview {
          display: block;
        }
      }
    }
    .picture-img {
      width: 100%;
      border-radius: 4px;
    }
    .picture-name {
      padding-top: 12px;
      color: #000000;
      padding-bottom: 6px;
      cursor: pointer;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      line-clamp: 2;
      -webkit-box-orient: vertical;
    }
  }
  .picture-item:hover {
    .picture-name:hover {
      display: block;
      color: #29ba9c;
    }
  }

  .overlay {
    position: fixed;
    z-index: 10;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100vw;
    height: 100vh;
    overflow: hidden;
    background-color: rgba(0, 0, 0, 0.7);
    .overlay-img-box {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
      width: 50vw;
      height: 50vw;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
</style>
